var userCode = null;
var userName = null;
var userPassword = null;
var ruserPassword = null;
var phone = null;
var birthday = null;
var userRole = null;
var addBtn = null;
var backBtn = null;


$(function () {
    userCode = $("#userCode");
    userName = $("#userName");
    userPassword = $("#userPassword");
    ruserPassword = $("#ruserPassword");
    phone = $("#phone");
    birthday = $("#birthday");
    userRole = $("#userRole");
    addBtn = $("#add");
    backBtn = $("#back");
    
    // 初始化的时候，要把所有的提示信息变为：* 以提示必填项，更灵活，不要写在页面上
    userCode.next().html("*");
    userName.next().html("*");
    userPassword.next().html("*");
    ruserPassword.next().html("*");
    phone.next().html("*");
    birthday.next().html("*");
    userRole.next().html("*");
    
    // 初始化所有字段的验证状态为false
    userCode.attr("validateStatus", "false");
    userName.attr("validateStatus", "false");
    userPassword.attr("validateStatus", "false");
    ruserPassword.attr("validateStatus", "false");
    phone.attr("validateStatus", "false");
    birthday.attr("validateStatus", "false");
    userRole.attr("validateStatus", "false");

    $.ajax({
        type: "GET",//请求类型
        url: path + "/jsp/user.do",//请求的url
        data: {method: "getrolelist"},//请求参数
        dataType: "json",//ajax接口（请求url）返回的数据类型
        success: function (data) {//data：返回数据（json对象）
            if (data != null) {
                userRole.html("");
                var options = "<option value=\"0\">请选择</option>";
                for (var i = 0; i < data.length; i++) {
                    options += "<option value=\"" + data[i].id + "\">" + data[i].roleName + "</option>";
                }
                userRole.html(options);
                
                // 如果有回显的角色数据，设置选中状态
                var selectedRole = userRole.attr("data-selected");
                if (selectedRole && selectedRole != "0") {
                    userRole.val(selectedRole);
                }
            }
        },
        error: function (data) {//当访问时候，404，500 等非200的错误状态码
            validateTip(userRole.next(), {"color": "red"}, imgNo + " 获取用户角色列表error", false);
        }
    });


    /*
     * 验证
     * 失焦\获焦
     * jquery的方法传递
     */
    userCode.bind("blur", function () {
        // 首先验证用户编码是否为空
        if (userCode.val() == null || userCode.val().trim() == "") {
            validateTip(userCode.next(), {"color": "red"}, imgNo + " 用户编码不能为空", false);
            return;
        }
        
        //ajax后台验证--userCode是否已存在
        //user.do?method=ucexist&userCode=**
        $.ajax({
            type: "GET",//请求类型
            url: path + "/jsp/user.do",//请求的url
            data: {method: "ucexist", userCode: userCode.val()},//请求参数
            dataType: "json",//ajax接口（请求url）返回的数据类型
            success: function (data) {//data：返回数据（json对象）
                if (data.userCode == "exist") {//账号已存在，错误提示
                    validateTip(userCode.next(), {"color": "red"}, imgNo + " 该用户账号已存在", false);
                } else {//账号可用，正确提示
                    validateTip(userCode.next(), {"color": "green"}, imgYes + " 该账号可以使用", true);
                }
            },
            error: function (data) {//当访问时候，404，500 等非200的错误状态码
                validateTip(userCode.next(), {"color": "red"}, imgNo + " 您访问的页面不存在", false);
            }
        });


    }).bind("focus", function () {
        //显示友情提示
        validateTip(userCode.next(), {"color": "#666666"}, "* 用户编码是您登录系统的账号", false);
    }).focus();

    userName.bind("focus", function () {
        validateTip(userName.next(), {"color": "#666666"}, "* 用户名长度必须是大于1小于10的字符", false);
    }).bind("blur", function () {
        if (userName.val() != null && userName.val().trim() != "" && userName.val().length > 1
            && userName.val().length < 10) {
            validateTip(userName.next(), {"color": "green"}, imgYes, true);
        } else {
            validateTip(userName.next(), {"color": "red"}, imgNo + " 用户名输入的不符合规范，请重新输入", false);
        }

    });

    userPassword.bind("focus", function () {
        validateTip(userPassword.next(), {"color": "#666666"}, "* 密码长度必须是大于6小于20", false);
    }).bind("blur", function () {
        if (userPassword.val() != null && userPassword.val().trim() != "" && userPassword.val().length > 6
            && userPassword.val().length < 20) {
            validateTip(userPassword.next(), {"color": "green"}, imgYes, true);
        } else {
            validateTip(userPassword.next(), {"color": "red"}, imgNo + " 密码输入不符合规范，请重新输入", false);
        }
    });

    ruserPassword.bind("focus", function () {
        validateTip(ruserPassword.next(), {"color": "#666666"}, "* 请输入与上面一只的密码", false);
    }).bind("blur", function () {
        if (ruserPassword.val() != null && ruserPassword.val().trim() != "" && ruserPassword.val().length > 6
            && ruserPassword.val().length < 20 && userPassword.val() == ruserPassword.val()) {
            validateTip(ruserPassword.next(), {"color": "green"}, imgYes, true);
        } else {
            validateTip(ruserPassword.next(), {"color": "red"}, imgNo + " 两次密码输入不一致，请重新输入", false);
        }
    });


    birthday.bind("focus", function () {
        validateTip(birthday.next(), {"color": "#666666"}, "* 点击输入框，选择日期", false);
    }).bind("blur", function () {
        if (birthday.val() != null && birthday.val().trim() != "") {
            // 验证日期格式是否正确 (yyyy-MM-dd)
            var datePattern = /^\d{4}-\d{2}-\d{2}$/;
            if (datePattern.test(birthday.val())) {
                // 验证日期是否有效
                var selectedDate = new Date(birthday.val());
                var today = new Date();
                if (selectedDate <= today && selectedDate.getFullYear() > 1900) {
                    validateTip(birthday.next(), {"color": "green"}, imgYes, true);
                } else {
                    validateTip(birthday.next(), {"color": "red"}, imgNo + " 日期无效，请选择有效日期", false);
                }
            } else {
                validateTip(birthday.next(), {"color": "red"}, imgNo + " 日期格式不正确，请选择日期", false);
            }
        } else {
            validateTip(birthday.next(), {"color": "red"}, imgNo + " 请选择出生日期", false);
        }
        
        // 调试：检查验证状态是否正确设置
        console.log("生日验证状态:", birthday.attr("validateStatus"));
    });

    phone.bind("focus", function () {
        validateTip(phone.next(), {"color": "#666666"}, "* 请输入手机号", false);
    }).bind("blur", function () {
        if (phone.val() != null && phone.val().trim() != "") {
            var patrn = /^(13[0-9]|15[0-9]|18[0-9])\d{8}$/;
            if (phone.val().match(patrn)) {
                validateTip(phone.next(), {"color": "green"}, imgYes, true);
            } else {
                validateTip(phone.next(), {"color": "red"}, imgNo + " 您输入的手机号格式不正确", false);
            }
        } else {
            validateTip(phone.next(), {"color": "red"}, imgNo + " 手机号不能为空", false);
        }
    });

    userRole.bind("focus", function () {
        validateTip(userRole.next(), {"color": "#666666"}, "* 请选择用户角色", false);
    }).bind("blur", function () {
        if (userRole.val() != null && userRole.val() > 0) {
            validateTip(userRole.next(), {"color": "green"}, imgYes, true);
        } else {
            validateTip(userRole.next(), {"color": "red"}, imgNo + " 请重新选择用户角色", false);
        }
    });

    // 阻止表单的默认提交行为，确保只有通过JavaScript验证才能提交
    $("#userForm").on("submit", function(e) {
        e.preventDefault(); // 阻止默认提交
        
        // 直接调用验证逻辑
        validateAndSubmit();
    });

    // 提交按钮点击事件
    addBtn.bind("click", function () {
        validateAndSubmit();
    });

    // 验证并提交的函数
    function validateAndSubmit() {
        // 强制触发所有字段的验证
        userCode.blur();
        userName.blur();
        userPassword.blur();
        ruserPassword.blur();
        birthday.blur();
        phone.blur();
        userRole.blur();
        
        // 等待验证完成后检查状态，增加延迟时间确保验证完成
        setTimeout(function() {
            // 调试：输出所有字段的验证状态
            console.log("用户编码验证状态:", userCode.attr("validateStatus"));
            console.log("用户名验证状态:", userName.attr("validateStatus"));
            console.log("密码验证状态:", userPassword.attr("validateStatus"));
            console.log("确认密码验证状态:", ruserPassword.attr("validateStatus"));
            console.log("生日验证状态:", birthday.attr("validateStatus"));
            console.log("电话验证状态:", phone.attr("validateStatus"));
            console.log("角色验证状态:", userRole.attr("validateStatus"));
            
            if (userCode.attr("validateStatus") != "true") {
                userCode.focus();
                return;
            } else if (userName.attr("validateStatus") != "true") {
                userName.focus();
                return;
            } else if (userPassword.attr("validateStatus") != "true") {
                userPassword.focus();
                return;
            } else if (ruserPassword.attr("validateStatus") != "true") {
                ruserPassword.focus();
                return;
            } else if (birthday.attr("validateStatus") != "true") {
                birthday.focus();
                return;
            } else if (phone.attr("validateStatus") != "true") {
                phone.focus();
                return;
            } else if (userRole.attr("validateStatus") != "true") {
                userRole.focus();
                return;
            } else {
                // 最终验证：检查所有字段是否都有值
                if (userCode.val().trim() == "" || userName.val().trim() == "" || 
                    userPassword.val().trim() == "" || ruserPassword.val().trim() == "" ||
                    birthday.val().trim() == "" || phone.val().trim() == "" || 
                    userRole.val() == "0") {
                    alert("请填写所有必填字段！");
                    return;
                }
                
                if (confirm("是否确认提交数据")) {
                    $("#userForm").submit();
                }
            }
        }, 200); // 增加延迟时间到200ms
    }

    backBtn.on("click", function () {
        if (referer != undefined
            && null != referer
            && "" != referer
            && "null" != referer
            && referer.length > 4) {
            window.location.href = referer;
        } else {
            history.back(-1);
        }
    });
});